<!-- filepath: f:\WebUI\waimai\src\pages\merchant\modals\ProductSpecsModal.vue -->
<template>
  <view v-if="visible" class="spec-modal" @tap="handleClose">
    <view class="spec-content" @tap.stop>
      <!-- 商品头部 -->
      <view class="spec-header">
        <image :src="product.image" class="spec-image"></image>
        <view class="spec-info">
          <text class="spec-name">{{ product.name }}</text>
          <text class="spec-price">¥{{ currentPrice.toFixed(2) }}</text>
        </view>
        <view class="close-btn" @tap="handleClose">
          <uni-icons type="closeempty" size="24" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 规格选择区域 -->
      <scroll-view class="spec-body" scroll-y>
        <!-- ⭐ 动态渲染口味选项（根据后端返回的tastes） -->
        <view 
          v-for="taste in product.tastes" 
          :key="taste.tasteId"
          class="spec-section"
        >
          <text class="spec-title">{{ taste.name }}</text>
          <view class="spec-options">
            <view 
              v-for="option in parseTasteOptions(taste.options)" 
              :key="option"
              class="spec-option"
              :class="{ active: selectedTastes[taste.tasteId] === option }"
              @tap="selectTaste(taste.tasteId, option, taste.extraPrice)"
            >
              {{ option }}
              <text v-if="taste.extraPrice > 0" class="extra-price">
                +¥{{ taste.extraPrice }}
              </text>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 底部操作栏 -->
      <view class="spec-footer">
        <view class="spec-control">
          <view class="cart-btn minus" @tap="decreaseCount">
            <uni-icons type="minus" size="16" color="#00C853"></uni-icons>
          </view>
          <text class="cart-count">{{ count }}</text>
          <view class="cart-btn plus" @tap="increaseCount">
            <uni-icons type="plus" size="16" color="#fff"></uni-icons>
          </view>
        </view>
        <view class="add-to-cart-btn" @tap="handleConfirm">
          加入购物车 ¥{{ totalPrice.toFixed(2) }}
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';

interface Taste {
  tasteId: number;
  name: string;
  options: string; // JSON字符串格式: ["微辣","中辣","特辣"]
  extraPrice: number;
}

interface Product {
  id: number;
  name: string;
  image: string;
  price: number;
  tastes?: Taste[];
}

interface Props {
  visible: boolean;
  product: Product;
}

const props = defineProps<Props>();
const emit = defineEmits(['close', 'confirm']);

// 选中的口味（key: tasteId, value: 选中的选项）
const selectedTastes = ref<Record<number, string>>({});
// 额外价格累计
const extraPriceTotal = ref(0);
// 数量
const count = ref(1);

// ⭐ 解析口味选项（JSON字符串转数组）
const parseTasteOptions = (optionsStr: string): string[] => {
  try {
    if (!optionsStr) return [];
    const parsed = JSON.parse(optionsStr);
    return Array.isArray(parsed) ? parsed : [];
  } catch (error) {
    console.error('解析口味选项失败:', optionsStr, error);
    return [];
  }
};

// ⭐ 选择口味
const selectTaste = (tasteId: number, option: string, extraPrice: number) => {
  // 如果重复选择相同选项，不做处理
  if (selectedTastes.value[tasteId] === option) return;
  
  // 更新选中的口味
  const oldOption = selectedTastes.value[tasteId];
  selectedTastes.value[tasteId] = option;
  
  // 更新额外价格（如果之前已选过，需要先减去旧价格）
  if (oldOption) {
    // 简化处理：每次重新计算所有额外价格
    calculateExtraPrice();
  } else {
    extraPriceTotal.value += extraPrice;
  }
};

// 重新计算额外价格
const calculateExtraPrice = () => {
  let total = 0;
  if (props.product.tastes) {
    props.product.tastes.forEach(taste => {
      if (selectedTastes.value[taste.tasteId]) {
        total += taste.extraPrice || 0;
      }
    });
  }
  extraPriceTotal.value = total;
};

// 计算当前单价（基础价格 + 额外价格）
const currentPrice = computed(() => {
  return props.product.price + extraPriceTotal.value;
});

// 计算总价
const totalPrice = computed(() => {
  return currentPrice.value * count.value;
});

// 增加数量
const increaseCount = () => {
  count.value++;
};

// 减少数量
const decreaseCount = () => {
  if (count.value > 1) {
    count.value--;
  }
};

// 关闭弹窗
const handleClose = () => {
  // 重置状态
  selectedTastes.value = {};
  extraPriceTotal.value = 0;
  count.value = 1;
  emit('close');
};

// ⭐ 确认添加到购物车
const handleConfirm = () => {
  // 检查是否所有必选项都已选择
  if (props.product.tastes && props.product.tastes.length > 0) {
    const unselectedTaste = props.product.tastes.find(
      taste => !selectedTastes.value[taste.tasteId]
    );
    
    if (unselectedTaste) {
      uni.showToast({
        title: `请选择${unselectedTaste.name}`,
        icon: 'none'
      });
      return;
    }
  }
  
  // 生成规格字符串（用于显示）
  const specsArray: string[] = [];
  if (props.product.tastes) {
    props.product.tastes.forEach(taste => {
      const selected = selectedTastes.value[taste.tasteId];
      if (selected) {
        specsArray.push(`${taste.name}:${selected}`);
      }
    });
  }
  const specs = specsArray.join(' / ');
  
  // 返回数据给父组件
  emit('confirm', {
    product: props.product,
    specs: specs,
    count: count.value,
    price: currentPrice.value
  });
  
  // 关闭弹窗并重置
  handleClose();
};

// 监听弹窗打开，重置状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    selectedTastes.value = {};
    extraPriceTotal.value = 0;
    count.value = 1;
  }
});
</script>

<style scoped>
.spec-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  z-index: 999;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}

.spec-content {
  background-color: #fff;
  max-height: 80vh;
  border-radius: 20rpx 20rpx 0 0;
  display: flex;
  flex-direction: column;
}

.spec-header {
  position: relative;
  display: flex;
  padding: 30rpx;
  gap: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.spec-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
}

.spec-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 10rpx;
}

.spec-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.spec-price {
  font-size: 32rpx;
  color: #ff3b30;
  font-weight: bold;
}

.close-btn {
  position: absolute;
  top: 30rpx;
  right: 30rpx;
}

.spec-body {
  flex: 1;
  padding: 30rpx;
}

.spec-section {
  margin-bottom: 40rpx;
}

.spec-title {
  display: block;
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.spec-options {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.spec-option {
  padding: 15rpx 30rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  font-size: 26rpx;
  color: #666;
  border: 2rpx solid transparent;
  display: flex;
  align-items: center;
  gap: 5rpx;
}

.spec-option.active {
  background-color: #e6f7ed;
  color: #00C853;
  border-color: #00C853;
}

.extra-price {
  font-size: 22rpx;
  color: #ff3b30;
}

.spec-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.spec-control {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.cart-btn {
  width: 44rpx;
  height: 44rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-btn.minus {
  border: 2rpx solid #00C853;
  background-color: #fff;
}

.cart-btn.plus {
  background-color: #00C853;
}

.cart-count {
  font-size: 28rpx;
  color: #333;
  min-width: 40rpx;
  text-align: center;
}

.add-to-cart-btn {
  flex: 1;
  padding: 20rpx;
  background-color: #00C853;
  color: #fff;
  font-size: 28rpx;
  font-weight: bold;
  border-radius: 40rpx;
  text-align: center;
  margin-left: 30rpx;
}
</style>